package com.hzit.manager.canallistener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.system.api.domain.Brand;
import com.xpand.starter.canal.annotation.DeleteListenPoint;
import com.xpand.starter.canal.annotation.InsertListenPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
// @CanalEventListener
@Slf4j
public class HzitCanalListener {

	@Autowired
	private RedisService redisService;
	/**
	 * 1. 当我们对hzitdb下的所有表执行插入操作时,将触发下面的代码
	 * @param eventType
	 * @param rowData
	 */
	@InsertListenPoint(table = "tb_brand")
	public void onInsertEvent(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
		// 1.1 获取插入后的列字段列表
		List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
		Brand brand = new Brand();
		// 1.2 代表添加的某一行的多个列(循环一条就得到一行数据)
		for (CanalEntry.Column column : afterColumnsList) {
			String name = column.getName();     // 列名
			String value = column.getValue();   // 插入的该列的值
			log.info("列名{},列值{}",name,value);
			if(name.equals("id")){
				brand.setId(Long.parseLong(value));
			}
			if(name.equals("name")){
				brand.setName(value);
			}
			if(name.equals("first_char")){
				brand.setFirstChar(value);
			}
		}
		redisService.setCacheMapValue(CacheConstants.BRAND_LIST,brand.getId() + "",brand);
	}

	/**
	 * 2. 执行删除操作
	 * @param eventType
	 * @param rowData
	 */
	@DeleteListenPoint(table = "tb_brand")
	public void onDeletePoint(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
		// 2.1 得到删除前的数据
		List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
		// 2.2 遍历删除前的数据
		for (CanalEntry.Column column : beforeColumnsList) {
			String name = column.getName();
			if(name.equals("id")){
				String value = column.getValue();
				redisService.deleteCacheMapValue(CacheConstants.BRAND_LIST,value);
				log.info("正在从redis中删除一条记录:id={}",value);
			}
		}
	}
}
